#!/usr/bin/php
<?php
$id=$argv[1];
$pid = getmypid();
$fp = fopen("/tmp/$id.pid","w");
fwrite($fp,$pid);
fclose($fp);
$loop = 0;
$temp = 80;
$temp1variance = 5;
$error = 0;
$connect = mysql_connect("localhost","beerwatch","beerwatch") or die(mysql_error());
$db = mysql_select_db("beerwatch",$connect);




//which id am I?
$lines = file("/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves");
$OK = false;
$order = -1;
for($i = 0;$i<sizeof($lines);$i++) {
	$lines[$i] = trim($lines[$i]);
	if ($lines[$i] == $id) {
		$order = $i;
		$order++;
	}
}
$probe_save=$order;

//this is all hosed up
$sql = "SELECT real_probe from probemap where probe=\"$order\"";
$result = mysql_query($sql,$connect);
$row = mysql_fetch_row($result);
$torder = $row[0];

//then get the real probe...
$ttorder=$torder;
$ttorder--;
$lines = file("/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves");
$id = $lines[$ttorder];
$id = trim($id);
if ($id == "") {
	exit;
}
$order=trim($torder);


$sql = "SELECT gpio from gpiotoheat where temp_index=\"$order\"";
$result = mysql_query($sql,$connect);
$row = mysql_fetch_row($result);
$gpio = $row[0];

$sql = "SELECT temp,variance from temps where temp_index=\"$order\"";

$result = mysql_query($sql,$connect);
$row = mysql_fetch_row($result);
$set_temp = $row[0];
$temp_variance = $row[1];
$isMash = false;
$isHLT = false;
$isGlycol = false;
while (42 == 42) {
	$OK = false;
	if ($set_temp > 0) {
		//here is where I would pull the temp, but for now, lets just read it..
		$reading = file("/sys/bus/w1/devices/".$id."/w1_slave");
		foreach($reading as $r) {
			$r = trim($r);
			if ($OK) {
				$temp = explode("=",$r);
				$temp = $temp[1];
				$temp = $temp/1000;
				$temp = ($temp*1.8000)+32.00;
				$temp = round($temp,2);
				//if ($i == 0) {
				//echo $temp ."\n";
				/* Somtimes the read fails, in which case we don't get here, so it's important to >= because if == and it fails, it will pass it, and thus never write to the db again */
				if ($loop >= 10) {
					$sql = "INSERT into currenttemps (readingtime,temp_index,temp) values (now(),\"$order\",\"$temp\")";
					$result = mysql_query($sql,$connect) or die(mysql_error());
					$loop=0;
					$fp = fopen("/tmp/checking.log","a");
					fwrite($fp,"Temp: $id: GPIO: $gpio: isOff: $i: Checking: $order: $gpio temp: $temp Set: $set_temp sql: $sql Starting....\n");
					fclose($fp);					

					//echo "Reset to $loop\n";
					$lines = file("/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves");
					$order = -1;
					for($i = 0;$i<sizeof($lines);$i++) {
					        $lines[$i] = trim($lines[$i]);
        					if ($lines[$i] == $id) {
	                				$order = $i;
                					$order++;
        					}
					}
					$sql = "SELECT gpio from gpiotoheat where temp_index=\"$probe_save\"";
					$result = mysql_query($sql,$connect);
					$row = mysql_fetch_row($result);
					$gpio = $row[0];
					

					$sql = "SELECT temp,variance from temps where temp_index=\"$torder\"";
					$result = mysql_query($sql,$connect);
					$row = mysql_fetch_row($result);
					$set_temp = $row[0];
					$temp_variance = $row[1];

					$fp = fopen("/tmp/checking.log","a");
					fwrite($fp,"Checking: $order: $gpio temp: $temp Set: $set_temp sql: $sql\n");
					fclose($fp);					
					
					$isHLT = isHLT($order);
					if ($isHLT) {
						//ok we need to convert the temp to the real temp
						$sql = "SELECT water_to_grain from temps where temp_index=\"$torder\"";
						$result = mysql_query($sql,$connect);
						$row = mysql_fetch_row($result);
						if ($row[0] == "") {
							$row[0] = 1.25;
						}
						$grain_temp = getMashProbeTemp();
						$water_to_grain = $row[0];
						$temp_variance=0;
						$set_temp = getStrikeTemp($grain_temp,$set_temp,$water_to_grain); 
						$sql = "UPDATE temps set real_temp=$set_temp where temp_index=\"$torder\"";
						$result = mysql_query($sql,$connect);
					}				
				
					
				}
				if (isOff($torder)) {
					$fp = fopen("/tmp/off","a");
					fwrite($fp,"Order: $torder\n");
					fclose($fp);
					$fp = fopen("/sys/class/gpio/gpio".$gpio."/value","r");
					$on = fread($fp,4096);
					fclose($fp);
					if ($on == 1) {
						$fp = fopen("/sys/class/gpio/gpio".$gpio."/value","w");
						fwrite($fp,"0\n");
 						fclose($fp);						
					}
				}
				#$fp = fopen("/tmp/requests","a");
				#$ii = isGlycol($order);
				#fwrite($fp,"Set temp $set_temp, Real Temp: $temp, Probe: $probe_save Order $order Glycol: $ii\n");
				#fclose($fp);

				$fp = fopen("/tmp/checking","a");
				fwrite($fp,"0: Temp: $temp  Set Temp: $set_temp\n");
				fclose($fp);

				if ($temp < $set_temp) {
					$fp = fopen("/tmp/checking","a");
					fwrite($fp,"1: $temp $set_temp\n");
					fclose($fp);
					$i = isOff($torder);
					if (!isMash($order) || !isGlycol($order)) {
						if (!isOff($torder)) {
							//see if we are already on
							$fp = fopen("/sys/class/gpio/gpio".$gpio."/value","r");
							$on = fread($fp,4096);
							fclose($fp);
							if ($on == 0 && $temp <= ($set_temp + $temp_variance) || round($set_temp) == round($temp)) {
								$fp = fopen("/sys/class/gpio/gpio".$gpio."/value","w");
								fwrite($fp,"1\n");
								fclose($fp);
							}
							$sql = "UPDATE glycol_requests set requests=0,set_temp=\"$set_temp\" where probe=$probe_save";
							$result = mysql_query($sql,$connect);

						}
					} 

				} else if (round($temp) > round($set_temp)) {
					if ($probe_save == 1) {
						$fp = fopen("/tmp/cool","a");
						fwrite($fp,"1: cool\n");
						fclose($fp);
						//turn the glycol on and open my entrace, I only have one fermentor right now so just turn the pump on
						$sql = "SELECT * from glycol_requests where probe=\"$probe_save\"";
						$result = mysql_query($sql,$connect);
						if(mysql_num_rows($result) == 0) {
							$sql = "INSERT into glycol_requests (probe,requests,set_temp) values ($probe_save,1,\"$set_temp\")";
							$result = mysql_query($sql,$connect);
						} else {
							$sql = "UPDATE glycol_requests set requests=1,set_temp=\"$set_temp\" where probe=$probe_save";
							$result = mysql_query($sql,$connect);
						}
					}
					//turn the heat off
					if (!isOff($torder)) {
                                        	$fp = fopen("/sys/class/gpio/gpio".$gpio."/value","r");
                                                $on = fread($fp,4096);
                                                fclose($fp);
                                                if ($on == 1 && $temp >= ($set_temp + $temp_variance)) {
                                                $fp = fopen("/sys/class/gpio/gpio".$gpio."/value","w");
                                                	fwrite($fp,"0\n");
                                                        fclose($fp);
                                                }
					}
					$fp = fopen("/tmp/checking","a");
					fwrite($fp,"2: $temp $set_temp\n");
					fclose($fp);
				} else {
					$fp = fopen("/tmp/checking","a");
					fwrite($fp,"3: $temp $set_temp\n");
					fclose($fp);
					if (!isMash($order) || !isGlycol($order)) {
        	                        	//see if we are already on
						$fp = fopen("/tmp/checking","a");
						fwrite($fp,"4: $temp $set_temp $temp_variance\n");
						fclose($fp);			
						if ($temp <= ($set_temp - $temp_variance) || round($temp) == round($set_temp)) {
							$sql = "UPDATE glycol_requests set requests=0 where probe=$probe_save";
							$result = mysql_query($sql,$connect);
						}

						if (!isOff($torder)) {
							$fp = fopen("/sys/class/gpio/gpio".$gpio."/value","r");
							$on = fread($fp,4096);
							fclose($fp);
							if ($on == 1 && $temp >= ($set_temp + $temp_variance)) {
								$fp = fopen("/sys/class/gpio/gpio".$gpio."/value","w");
								fwrite($fp,"0\n");
								fclose($fp);					
							}
							$fp = fopen("/tmp/requests","a");
							fwrite($fp, "Set temp: $set_temp Temp: $temp\n");
							fclose($fp);
						}
					}
				}
			}
			if (strstr($r,"YES") && $OK==false) {
				$OK = true;
			}
		}
	} else {
		if (isMash($order)) {
			$temp=getMashProbeTemp();
			if ($loop >= 10) {
				$sql = "INSERT into currenttemps (readingtime,temp_index,temp) values (now(),\"$order\",\"$temp\")";
				$result = mysql_query($sql,$connect) or die(mysql_error());
				$loop=0;
			}
			usleep(50000);
		} else {
			if ($error == 0) {
				echo "Temp is not set! You should be brewing on this!!!!  Make more beer!!\n";
				$error++;
			}
		}
	}	
	$loop++;
	//echo "Loop is: $loop Temp is: $temp\n";
	usleep(50000);
}

function isHLT($probe) {
	$connect = mysql_connect("localhost","beerwatch","beerwatch") or die(mysql_error());
	$db = mysql_select_db("beerwatch",$connect);
        $sql = "SELECT count(*) from hltmash where hlt_probe=\"$probe\"";
        $r = mysql_query($sql,$connect);
        $row = mysql_fetch_row($r);
        if ($row[0] >= 1) {
                return true;
        } else {
                return false;
        }

}

function isMASH($probe) {
	$connect = mysql_connect("localhost","beerwatch","beerwatch") or die(mysql_error());
	$db = mysql_select_db("beerwatch",$connect);
        $sql = "SELECT count(*) from hltmash where mash_probe=\"$probe\"";
        $r = mysql_query($sql,$connect);
        $row = mysql_fetch_row($r);
        if ($row[0] >= 1) {
                return true;
        } else {
                return false;
        }

}

function isGlycol($probe) {
	$connect = mysql_connect("localhost","beerwatch","beerwatch") or die(mysql_error());
	$db = mysql_select_db("beerwatch",$connect);
        $sql = "SELECT count(*) from hltmash where glycol_probe=\"$probe\"";
        $r = mysql_query($sql,$connect);
        $row = mysql_fetch_row($r);
        if ($row[0] >= 1) {
                return true;
        } else {
                return false;
        }

}

function getMashProbeTemp() {
        $connect = mysql_connect("localhost","beerwatch","beerwatch") or die(mysql_error());
        $db = mysql_select_db("beerwatch",$connect);
        $sql = "SELECT mash_probe from hltmash";
        $r = mysql_query($sql,$connect);
        $row = mysql_fetch_row($r);
        $tprobe = $row[0];
        $prid = "";
        $t = "";
        if ($tprobe != "") {
                //ok this is the probe number (which is actually the order - 1);
                $probes = file("/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves");
                $tprobe = $probe -1;
                $prid= $probes[$probe];
                $prid = trim($prid);
        }
        if ($prid != "") {
                //sometimes it dosen't read so lets make sure we get something
                while ($t == "") {
                        $t = getTempFromFile($prid);
                }
        }
        return $t;
}

function getTempFromFile($id) {
        $OK = false;
        $temp = "";
        $reading = file("/sys/bus/w1/devices/".$id."/w1_slave");
        foreach($reading as $r) {
                $r = trim($r);
                if ($OK) {
                        $temp = explode("=",$r);
                        $temp = $temp[1];
                        $temp = $temp/1000;
                        $temp = ($temp*1.8000)+32.00;
                        $temp = round($temp,2);
                }
                if (strstr($r,"YES") && $OK==false) {
                        $OK = true;
                }
        }
        return $temp;
}

function getStrikeTemp($grain_temp,$target_temp,$water_to_grain) {
        $a = .2/$water_to_grain;
        $b = $target_temp - $grain_temp;
        $c = $a * $b;
        $d = $c + $target_temp;
        return $d;
}


function isOff($probe) {
        $connect = mysql_connect("localhost","beerwatch","beerwatch") or die(mysql_error());
        $db = mysql_select_db("beerwatch",$connect);
        $sql = "SELECT off from temps where temp_index=\"$probe\"";
        $result = mysql_query($sql,$connect);
        if (mysql_num_rows($result) == 0) {
                return true;
        } else {
                $row = mysql_fetch_row($result);
                return $row[0];
        }
}

?>
